import React, {
  createContext,
  useContext,
  forwardRef,
  useImperativeHandle,
  useEffect,
  useCallback,
  useState,
  useRef,
} from 'react';
import { createPortal } from 'react-dom';
import { motion, AnimatePresence } from 'framer-motion';
import type {
  ModalSheetProps,
  ModalSheetContextValue,
  ModalSheetRef,
} from './types';
// 统一从 hooks/index.ts 导入所有钩子和工具
import {
  useModalSheet,
  useDraggable,
  usePortal,
  useSnapPoints,
  useAccessibility,
  useMultiDirectionResize,
  AnimationVariantGenerator,
  ANIMATION_PRESETS,
} from './hooks';
import './ModalSheet.css';
import './ModalSheet.theme.css';

// Modal Sheet 上下文
// 说明：提供 isOpen/close/size/position 等共享能力，避免 props 层层传递
// 好处：提升内聚性，降低耦合，子组件可以无感访问通用能力
const ModalSheetContext = createContext<ModalSheetContextValue | null>(null);

/**
 * 获取 Modal Sheet 上下文
 */
export const useModalSheetContext = () => {
  const context = useContext(ModalSheetContext);
  if (!context) {
    throw new Error('useModalSheetContext must be used within a ModalSheet');
  }
  return context;
};

/**
 * Modal Sheet 主组件
 *
 * 🎯 核心设计理念：
 * 1. 单一职责：专注于弹框的展示和基础交互
 * 2. 可组合性：通过多个 hooks 组合实现复杂功能
 * 3. 渐进增强：基础功能稳定，高级功能可选启用
 * 4. 类型安全：完整的 TypeScript 支持
 *
 * 🏗️ 架构设计：
 * - Portal 渲染：避免 z-index 层级问题
 * - Context 状态共享：子组件无感访问状态和方法
 * - Framer Motion 动画：流畅的进入退出动画
 * - 多 Hook 组合：每个 Hook 负责特定功能领域
 *
 * 🔧 技术要点：
 * - 所有 hooks 调用在组件顶部，避免条件调用错误
 * - 使用 flushSync 在用户交互中确保状态同步
 * - 通过 useImperativeHandle 暴露命令式 API
 * - 可选的主题系统集成，不影响基础功能
 */
export const ModalSheet = forwardRef<ModalSheetRef, ModalSheetProps>(
  (
    {
      open,
      onClose,
      children,
      snapPoints,
      initialSnap = 0,
      onSnap,
      size = 'medium',
      position = 'bottom',
      animation = 'slide',
      showOverlay: _showOverlay = true,
      closeOnOverlayClick = true,
      closeOnEscape = true,
      resizable = false,
      draggable = false,
      className = '',
      style,
      overlayClassName = '',
      overlayStyle,
      animationDuration = 300,
      animationPreset = 'smoothSlide',
      customAnimationConfig,
      enableAnimationEnhancements = true,
      zIndex = 1000,
      lockScroll = true,
      autoFocus = true,
      trapFocus = true,
      container,
      onBeforeOpen,
      onAfterOpen,
      onBeforeClose,
      onAfterClose,
      onDragStart,
      onDrag,
      onDragEnd,
    },
    ref
  ) => {
    // 基础能力统一管理：遮罩点击、ESC 关闭、锁滚动、焦点管理、生命周期回调
    const { modalRef, overlayRef, handleOverlayClick } = useModalSheet({
      open,
      onClose,
      closeOnEscape,
      closeOnOverlayClick,
      lockScroll,
      autoFocus,
      trapFocus,
      onBeforeOpen,
      onAfterOpen,
      onBeforeClose,
      onAfterClose,
    });

    // 自由拖拽（不含吸附点）：混合方案 - Framer Motion + 原生事件
    const {
      dragRef,
      isDragging: isDraggingPosition,
      position: dragPosition,
      handleMouseDown: nativeHandleMouseDown,
    } = useDraggable(draggable, onDragStart, onDrag, onDragEnd);

    // 高速拖拽检测
    const [isHighSpeedDrag, setIsHighSpeedDrag] = useState(false);
    const lastDragTime = useRef<number>(0);
    const dragVelocityThreshold = 500; // 像素/秒

    // 多方向可调整大小功能
    const {
      resetSize,
      availableDirections,
      getResizeHandleProps,
      resizeStyles,
    } = useMultiDirectionResize({
      enabled: resizable,
      position,
      draggable, // 传入拖拽状态，影响位置补偿逻辑
      minWidth: 200,
      minHeight: 150,
      onResizeStart: direction => {
        console.log('🔧 开始调整大小:', { direction, position });
      },
      onResize: (width, height) => {
        console.log('调整大小中:', { width, height });
      },
      onResizeEnd: () => {
        console.log('调整大小结束');
      },
    });

    // 调试信息
    console.log('🔧 Modal Sheet 调试信息:', {
      resizable,
      position,
      availableDirections,
      resizeHandleCount: availableDirections.length,
    });

    // 吸附点：负责尺寸计算（height/width）、拖拽中实时跟随、释放后就近吸附
    const {
      containerRef,
      currentSnapIndex,
      snapStyles,
      snapTo,
      handleDragStart: handleSnapDragStart,
      isDragging: isDraggingSnap,
      hasSnapPoints,
      isInitialized,
    } = useSnapPoints({
      snapPoints,
      initialSnap,
      onSnap,
      onClose,
      position,
      open,
    });

    const portalContainer = usePortal(container);

    // 可访问性支持
    const {
      handleKeyDown,
      getAriaProps,
      focusElement,
      announceChange,
      setElementRef,
    } = useAccessibility({
      enableKeyboardNavigation: true,
      enableScreenReader: true,
      enableFocusManagement: autoFocus,
      ariaLabel: `模态弹框 - ${position}位置`,
      ariaDescription: hasSnapPoints
        ? `可拖拽的模态弹框，支持 ${snapPoints?.length || 0} 个吸附点`
        : '可拖拽的模态弹框',
      ariaValueText: hasSnapPoints
        ? `当前位置：第 ${currentSnapIndex + 1} 个吸附点，共 ${snapPoints?.length || 0} 个`
        : '',
    });

    // 主题系统支持（可选）
    // let themeContext = null;
    // try {
    //   themeContext = useTheme();
    // } catch {
    //   // 如果没有 ThemeProvider，则忽略主题功能
    // }

    // 暴露 Ref 方法：保持最小 API 面，方便外部控制且不泄露内部实现
    useImperativeHandle(
      ref,
      () => ({
        snapTo,
        getCurrentSnap: () => currentSnapIndex,
        close: onClose,
        focusElement, // 暴露焦点管理方法
        announceChange, // 暴露状态宣布方法
      }),
      [snapTo, currentSnapIndex, onClose, focusElement, announceChange]
    );

    // 焦点管理：弹框打开时自动聚焦
    useEffect(() => {
      if (open && autoFocus) {
        focusElement();
      }
    }, [open, autoFocus, focusElement]);

    // 状态变化通知
    useEffect(() => {
      if (hasSnapPoints && open) {
        const snapValue = snapPoints?.[currentSnapIndex];
        if (snapValue !== undefined) {
          announceChange(
            `当前位置：第 ${currentSnapIndex + 1} 个吸附点，共 ${snapPoints?.length || 0} 个`
          );
        }
      }
    }, [currentSnapIndex, hasSnapPoints, snapPoints, open, announceChange]);

    // 重置调整大小状态（当modal关闭时）
    useEffect(() => {
      if (!open) {
        resetSize();
      }
    }, [open, resetSize]);

    // 强制样式更新（修复初始渲染问题）
    useEffect(() => {
      if (open && hasSnapPoints) {
        // 立即强制更新拖拽条样式
        const timer = setTimeout(() => {
          const dragArea = document.querySelector('.modal-sheet__drag-area');
          const indicator = document.querySelector(
            '.modal-sheet__drag-indicator'
          );

          if (dragArea) {
            const element = dragArea as HTMLElement;
            // 只保留关键的显示修复
            element.style.setProperty('display', 'flex', 'important');
            element.style.setProperty('visibility', 'visible', 'important');
            element.style.setProperty('opacity', '1', 'important');

            // 强制修复父元素的overflow问题
            const modalSheet = element.closest('.modal-sheet') as HTMLElement;
            if (modalSheet) {
              modalSheet.style.setProperty('overflow', 'visible', 'important');
            }
          }

          if (indicator) {
            const indicatorEl = indicator as HTMLElement;
            // 只保留关键的显示修复
            indicatorEl.style.setProperty('display', 'block', 'important');
            indicatorEl.style.setProperty('visibility', 'visible', 'important');
            indicatorEl.style.setProperty('opacity', '1', 'important');
          }
        }, 10); // 很短的延迟，确保DOM已渲染

        return () => clearTimeout(timer);
      }
    }, [open, hasSnapPoints]);

    // DOM元素检查（调试用）
    useEffect(() => {
      if (open && (draggable || hasSnapPoints)) {
        setTimeout(() => {
          const dragArea = document.querySelector('.modal-sheet__drag-area');
          const dragIndicator = document.querySelector(
            '.modal-sheet__drag-indicator'
          );
          const modalSheet = document.querySelector('.modal-sheet');

          console.log('🔍 DOM元素检查:', {
            dragArea: dragArea ? '存在' : '不存在',
            dragIndicator: dragIndicator ? '存在' : '不存在',
            modalSheet: modalSheet ? '存在' : '不存在',
          });

          if (dragArea) {
            console.log('🎯 拖拽区域计算样式:', {
              display: window.getComputedStyle(dragArea).display,
              visibility: window.getComputedStyle(dragArea).visibility,
              opacity: window.getComputedStyle(dragArea).opacity,
              zIndex: window.getComputedStyle(dragArea).zIndex,
              width: window.getComputedStyle(dragArea).width,
              height: window.getComputedStyle(dragArea).height,
              top: window.getComputedStyle(dragArea).top,
              position: window.getComputedStyle(dragArea).position,
            });
          }

          if (modalSheet) {
            console.log('🏠 Modal整体样式:', {
              height: window.getComputedStyle(modalSheet).height,
              minHeight: window.getComputedStyle(modalSheet).minHeight,
              maxHeight: window.getComputedStyle(modalSheet).maxHeight,
              transform: window.getComputedStyle(modalSheet).transform,
            });
          }
        }, 100);
      }
    }, [open, draggable, hasSnapPoints]);

    // 键盘事件处理：集成可访问性支持
    const handleKeyDownEvent = useCallback(
      (event: React.KeyboardEvent) => {
        // 处理基础键盘事件
        handleKeyDown(event.nativeEvent);

        // 处理 Snap Points 相关的键盘导航
        if (hasSnapPoints && snapPoints) {
          switch (event.key) {
            case 'ArrowUp':
              event.preventDefault();
              if (currentSnapIndex > 0) {
                snapTo(currentSnapIndex - 1);
                announceChange(`移动到第 ${currentSnapIndex} 个吸附点`);
              }
              break;

            case 'ArrowDown':
              event.preventDefault();
              if (currentSnapIndex < snapPoints.length - 1) {
                snapTo(currentSnapIndex + 1);
                announceChange(`移动到第 ${currentSnapIndex + 2} 个吸附点`);
              }
              break;

            case 'Home':
              event.preventDefault();
              snapTo(0);
              announceChange('移动到第一个吸附点');
              break;

            case 'End':
              event.preventDefault();
              snapTo(snapPoints.length - 1);
              announceChange('移动到最后一个吸附点');
              break;

            case 'Escape':
              event.preventDefault();
              onClose();
              announceChange('弹框已关闭');
              break;

            default:
              break;
          }
        } else if (event.key === 'Escape' && closeOnEscape) {
          // 非 Snap Points 模式下的 ESC 关闭
          event.preventDefault();
          onClose();
          announceChange('弹框已关闭');
        }
      },
      [
        handleKeyDown,
        hasSnapPoints,
        snapPoints,
        currentSnapIndex,
        snapTo,
        announceChange,
        onClose,
        closeOnEscape,
      ]
    );

    // 动画变体：支持增强动画效果
    const getAnimationVariants = useCallback(() => {
      if (!enableAnimationEnhancements) {
        // 使用原始简单动画
        switch (position) {
          case 'bottom':
            return {
              hidden: { opacity: 0, y: '100%' },
              visible: { opacity: 1, y: 0 },
              exit: { opacity: 0, y: '100%' },
            };
          case 'top':
            return {
              hidden: { opacity: 0, y: '-100%' },
              visible: { opacity: 1, y: 0 },
              exit: { opacity: 0, y: '-100%' },
            };
          case 'left':
            return {
              hidden: { opacity: 0, x: '100%' },
              visible: { opacity: 1, x: 0 },
              exit: { opacity: 0, x: '100%' },
            };
          case 'right':
            return {
              hidden: { opacity: 0, x: '-100%' },
              visible: { opacity: 1, x: 0 },
              exit: { opacity: 0, x: '-100%' },
            };
          default:
            return {
              hidden: { opacity: 0 },
              visible: { opacity: 1 },
              exit: { opacity: 0 },
            };
        }
      }

      // 使用增强动画
      let generator: AnimationVariantGenerator;

      if (animationPreset === 'custom' && customAnimationConfig) {
        // 自定义动画配置
        generator = new AnimationVariantGenerator(
          {
            duration: animationDuration,
            easing: customAnimationConfig.easing as any,
            enableSpring: customAnimationConfig.enableSpring,
            spring: customAnimationConfig.spring,
          },
          customAnimationConfig.chainAnimation
        );
      } else {
        // 使用预设动画
        const presetKey =
          animationPreset === 'custom' ? 'smoothSlide' : animationPreset;
        generator =
          ANIMATION_PRESETS[presetKey as keyof typeof ANIMATION_PRESETS] ||
          ANIMATION_PRESETS.smoothSlide;

        // 更新持续时间
        generator = new AnimationVariantGenerator(
          {
            ...generator.animationConfig,
            duration: animationDuration,
          },
          generator.chainAnimationConfig
        );
      }

      // 根据动画类型和位置生成变体
      switch (animation) {
        case 'slide':
          return generator.generateSlideVariants(position);
        case 'scale':
          return generator.generateScaleVariants();
        case 'fade':
          return generator.generateFadeVariants();
        case 'bounce':
          return generator.generateBounceVariants();
        case 'none':
          return {
            hidden: { opacity: 1 },
            visible: { opacity: 1 },
            exit: { opacity: 1 },
          };
        default:
          return generator.generateSlideVariants(position);
      }
    }, [
      enableAnimationEnhancements,
      position,
      animation,
      animationPreset,
      customAnimationConfig,
      animationDuration,
    ]);

    // 如果没有 portal 容器，不渲染
    if (!portalContainer) {
      return null;
    }

    // 构建样式类名：按位置/尺寸/动画/能力组合，样式可组合、易扩展
    const overlayClasses = [
      'modal-sheet-overlay',
      `modal-sheet-overlay--${animation}`,
      overlayClassName,
    ]
      .filter(Boolean)
      .join(' ');

    const modalClasses = [
      'modal-sheet',
      `modal-sheet--${position}`,
      `modal-sheet--${size}`,
      `modal-sheet--${animation}`,
      draggable && 'modal-sheet--draggable',
      (isDraggingPosition || isDraggingSnap) && 'modal-sheet--dragging',
      resizable && 'modal-sheet--resizable',
      hasSnapPoints && 'modal-sheet--snap-points',
      className,
    ]
      .filter(Boolean)
      .join(' ');

    // 构建内联样式：
    // - 自由拖拽：transform 平移
    // - 吸附点：通过 height/width 过渡，避免与 transform 冲突
    const overlayStyles: React.CSSProperties = {
      zIndex,
      ...overlayStyle,
    };

    const modalStyles: React.CSSProperties = {
      // 高速拖拽时使用原生 transform，否则让 Framer Motion 处理
      ...(isHighSpeedDrag && isDraggingPosition
        ? {
            transform: `translate(${dragPosition.x}px, ${dragPosition.y}px)`,
            transition: 'none', // 确保拖拽时没有过渡动画
          }
        : {}),
      ...(hasSnapPoints ? snapStyles : {}),
      // 确保Snap Points模式下有最小高度
      ...(hasSnapPoints && (!snapStyles || !snapStyles.height)
        ? { height: '100px' }
        : {}),
      // 应用调整大小的样式（但排除位置相关属性，避免与拖拽冲突）
      ...(() => {
        if (!resizeStyles) return {};

        // 检查弹框是否有拖拽偏移（不管当前是否在拖拽）
        const hasDragOffset = dragPosition.x !== 0 || dragPosition.y !== 0;

        // 如果弹框可拖拽，调整大小时总是过滤位置样式，避免位置跳跃
        // 或者正在拖拽、高速拖拽或有拖拽偏移时也过滤
        if (
          draggable ||
          isDraggingPosition ||
          isHighSpeedDrag ||
          hasDragOffset
        ) {
          const filteredStyles: React.CSSProperties = {};
          Object.keys(resizeStyles).forEach(key => {
            // 只保留尺寸相关的样式，排除位置相关的样式
            if (!['left', 'top', 'position'].includes(key)) {
              (filteredStyles as any)[key] = (resizeStyles as any)[key];
            }
          });
          console.log('🔧 过滤位置样式:', {
            draggable,
            isDraggingPosition,
            isHighSpeedDrag,
            hasDragOffset,
            dragPosition,
            reason: draggable
              ? '弹框可拖拽'
              : hasDragOffset
                ? '有拖拽偏移'
                : '正在拖拽',
            originalStyles: Object.keys(resizeStyles),
            filteredStyles: Object.keys(filteredStyles),
          });
          return filteredStyles;
        }

        // 如果没有拖拽偏移，应用完整的调整大小样式
        console.log('🔧 应用完整调整大小样式:', {
          hasDragOffset,
          dragPosition,
          resizeStyles: Object.keys(resizeStyles),
        });
        return resizeStyles;
      })(),
      ...style,
    };

    // 调试信息
    if (process.env.NODE_ENV === 'development') {
      // 调整大小方向调试
      if (resizable && open) {
        console.log('🔧 可调整大小方向:', {
          position,
          availableDirections,
          enabled: resizable,
        });
      }

      // 拖拽条显示调试
      if (open) {
        console.log('🔍 拖拽条显示状态:', {
          draggable,
          hasSnapPoints,
          shouldShowDragArea: draggable || hasSnapPoints,
          position,
          size,
          snapPoints: snapPoints,
          snapPointsLength: snapPoints?.length || 0,
          currentSnapIndex,
          isInitialized,
          snapStyles: hasSnapPoints ? JSON.stringify(snapStyles) : null,
        });
      }

      // 拖拽状态调试
      if (isDraggingPosition) {
        console.log('🎯 普通拖拽状态:', {
          isDraggingPosition,
          dragPosition,
          isHighSpeedDrag,
          dragMode: isHighSpeedDrag
            ? '🚀 原生高速模式'
            : '🎭 Framer Motion模式',
          modalStyles: JSON.stringify(modalStyles),
          className: modalClasses,
          animateValue: isDraggingPosition ? false : 'visible',
          usingFramerMotionDrag:
            draggable && !hasSnapPoints && !isHighSpeedDrag,
          usingNativeDrag: isHighSpeedDrag && isDraggingPosition,
        });
      }

      // 调整大小与拖拽冲突调试
      if (resizable && resizeStyles) {
        const hasDragOffset = dragPosition.x !== 0 || dragPosition.y !== 0;
        console.log('🔧 调整大小样式应用调试:', {
          position,
          isResizing: !!resizeStyles,
          isDraggingPosition,
          isHighSpeedDrag,
          hasDragOffset,
          dragPosition,
          resizeStyles: JSON.stringify(resizeStyles),
          appliedStyles: JSON.stringify(modalStyles),
          willFilterPositionStyles:
            draggable || isDraggingPosition || isHighSpeedDrag || hasDragOffset,
        });
      }
    }

    // 上下文值：对外只暴露必要状态与动作，隐藏实现细节
    const contextValue: ModalSheetContextValue = {
      isOpen: open,
      close: onClose,
      size,
      position,
      draggable,
      resizable,
    };

    const modalContent = (
      <AnimatePresence mode='wait'>
        {open && (
          <motion.div
            ref={overlayRef}
            className={overlayClasses}
            style={overlayStyles}
            onClick={handleOverlayClick}
            aria-hidden={!open}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: animationDuration / 1000 }}
          >
            <motion.div
              ref={node => {
                if (modalRef) {
                  (
                    modalRef as React.MutableRefObject<HTMLDivElement | null>
                  ).current = node;
                }
                if (dragRef) {
                  (
                    dragRef as React.MutableRefObject<HTMLDivElement | null>
                  ).current = node;
                }
                if (containerRef) {
                  (
                    containerRef as React.MutableRefObject<HTMLDivElement | null>
                  ).current = node;
                }
                // 设置可访问性元素引用
                setElementRef(node);
              }}
              className={modalClasses}
              style={modalStyles}
              // 可访问性属性
              {...getAriaProps()}
              onKeyDown={handleKeyDownEvent}
              variants={getAnimationVariants()}
              initial='hidden'
              animate={isDraggingPosition ? false : 'visible'} // 拖拽时禁用动画
              exit='exit'
              transition={
                isDraggingPosition
                  ? { duration: 0 } // 拖拽时禁用Framer Motion的过渡动画
                  : {
                      duration: animationDuration / 1000,
                      ease:
                        isDraggingSnap || isDraggingPosition
                          ? 'linear'
                          : 'easeOut',
                      delay: 0, // 移除延迟，确保拖拽条立即可见
                    }
              }
              // 🎯 使用 Framer Motion 的拖拽功能（仅在普通拖拽模式下，且非高速拖拽）
              drag={draggable && !hasSnapPoints && !isHighSpeedDrag}
              dragMomentum={false}
              dragElastic={0}
              dragTransition={{
                power: 0, // 移除惯性力
                timeConstant: 0, // 立即响应
                bounceStiffness: 0, // 移除弹性
                bounceDamping: 0, // 移除阻尼
              }}
              whileDrag={{
                scale: 1.02, // 拖拽时轻微放大
                zIndex: 9999, // 提升层级
                cursor: 'grabbing', // 改变光标
              }}
              onDragStart={(event, info) => {
                console.log('🎯 Framer Motion 拖拽开始:', info);
                onDragStart?.(event as MouseEvent | TouchEvent);
              }}
              onDrag={(event, info) => {
                const now = performance.now();
                const timeDelta = now - lastDragTime.current;
                const speed = Math.sqrt(
                  Math.pow(info.velocity.x, 2) + Math.pow(info.velocity.y, 2)
                );

                // 检测高速拖拽
                if (speed > dragVelocityThreshold && !isHighSpeedDrag) {
                  console.log('🚀 检测到高速拖拽，切换到原生处理模式');
                  setIsHighSpeedDrag(true);
                } else if (
                  speed < dragVelocityThreshold / 2 &&
                  isHighSpeedDrag
                ) {
                  console.log('🐌 拖拽速度降低，切换回 Framer Motion 模式');
                  setIsHighSpeedDrag(false);
                }

                console.log('🎯 Framer Motion 拖拽中:', {
                  point: info.point,
                  velocity: info.velocity,
                  speed: Math.round(speed),
                  timestamp: now,
                  timeDelta: Math.round(timeDelta),
                  isHighSpeed: isHighSpeedDrag,
                });

                lastDragTime.current = now;
                onDrag?.(event as MouseEvent | TouchEvent, {
                  x: info.point.x,
                  y: info.point.y,
                });
              }}
              onDragEnd={(event, info) => {
                console.log('🎯 Framer Motion 拖拽结束:', info.point);
                onDragEnd?.(event as MouseEvent | TouchEvent, {
                  x: info.point.x,
                  y: info.point.y,
                });
              }}
            >
              <ModalSheetContext.Provider value={contextValue}>
                {/* 拖拽区域：支持自由拖拽和吸附点拖拽 */}
                {(() => {
                  const shouldShow = draggable || hasSnapPoints;
                  // 简化的渲染检查日志，添加位置信息
                  if (process.env.NODE_ENV === 'development') {
                    console.log('🎯 拖拽条渲染:', {
                      draggable,
                      hasSnapPoints,
                      shouldShow,
                      position, // 添加位置信息
                      isSnapPointsTop: hasSnapPoints && position === 'top', // 特殊标记
                      modalClasses: `modal-sheet--${position}${hasSnapPoints ? ' modal-sheet--snap-points' : ''}`, // 显示应用的类名
                    });
                  }

                  // 如果应该显示但实际没显示，添加额外调试
                  if (shouldShow) {
                    setTimeout(() => {
                      // 强制清除可能的缓存样式，移除所有调试样式
                      const dragArea = document.querySelector(
                        '.modal-sheet__drag-area'
                      );
                      if (dragArea) {
                        const element = dragArea as HTMLElement;

                        // 先清除所有可能的调试样式，但保留关键的order属性
                        element.style.removeProperty('background');
                        element.style.removeProperty('border');
                        element.style.removeProperty('min-height');
                        element.style.removeProperty('z-index');
                        element.style.removeProperty('position');
                        // 不要移除order属性，因为它对拖拽条位置很重要
                        // element.style.removeProperty('order');

                        // 只保留关键的显示修复
                        element.style.setProperty(
                          'display',
                          'flex',
                          'important'
                        );
                        element.style.setProperty(
                          'visibility',
                          'visible',
                          'important'
                        );
                        element.style.setProperty('opacity', '1', 'important');

                        // 强制修复父元素overflow
                        const modalSheet = element.closest(
                          '.modal-sheet'
                        ) as HTMLElement;
                        if (modalSheet) {
                          modalSheet.style.setProperty(
                            'overflow',
                            'visible',
                            'important'
                          );
                        }
                      }

                      const indicator = document.querySelector(
                        '.modal-sheet__drag-indicator'
                      );
                      if (indicator) {
                        const indicatorEl = indicator as HTMLElement;

                        // 先清除可能的调试样式
                        indicatorEl.style.removeProperty('background');
                        indicatorEl.style.removeProperty('width');
                        indicatorEl.style.removeProperty('height');
                        indicatorEl.style.removeProperty('border');

                        // 只保留关键的显示修复
                        indicatorEl.style.setProperty(
                          'display',
                          'block',
                          'important'
                        );
                        indicatorEl.style.setProperty(
                          'visibility',
                          'visible',
                          'important'
                        );
                        indicatorEl.style.setProperty(
                          'opacity',
                          '1',
                          'important'
                        );
                      }

                      const modalSheet = document.querySelector('.modal-sheet');

                      if (dragArea) {
                        const rect = dragArea.getBoundingClientRect();
                        const parentRect = modalSheet
                          ? modalSheet.getBoundingClientRect()
                          : null;

                        console.log('🔍 DOM检查 - 拖拽区域详细信息:', {
                          exists: !!dragArea,
                          modalSheetClasses: modalSheet
                            ? modalSheet.className
                            : 'N/A',
                          dragAreaClasses: dragArea.className, // 添加拖拽区域的类名
                          // 位置信息
                          boundingRect: {
                            top: rect.top,
                            left: rect.left,
                            width: rect.width,
                            height: rect.height,
                            bottom: rect.bottom,
                            right: rect.right,
                          },
                          parentBoundingRect: parentRect
                            ? {
                                top: parentRect.top,
                                left: parentRect.left,
                                width: parentRect.width,
                                height: parentRect.height,
                              }
                            : null,
                          // 样式信息
                          computedStyles: {
                            display: window.getComputedStyle(dragArea).display,
                            visibility:
                              window.getComputedStyle(dragArea).visibility,
                            opacity: window.getComputedStyle(dragArea).opacity,
                            position:
                              window.getComputedStyle(dragArea).position,
                            zIndex: window.getComputedStyle(dragArea).zIndex,
                            overflow:
                              window.getComputedStyle(dragArea).overflow,
                            order: window.getComputedStyle(dragArea).order, // 添加order检查
                            background:
                              window.getComputedStyle(dragArea).background,
                            minHeight:
                              window.getComputedStyle(dragArea).minHeight,
                          },
                          // 父元素样式
                          parentStyles: modalSheet
                            ? {
                                overflow:
                                  window.getComputedStyle(modalSheet).overflow,
                                overflowX:
                                  window.getComputedStyle(modalSheet).overflowX,
                                overflowY:
                                  window.getComputedStyle(modalSheet).overflowY,
                                height:
                                  window.getComputedStyle(modalSheet).height,
                                maxHeight:
                                  window.getComputedStyle(modalSheet).maxHeight,
                                width:
                                  window.getComputedStyle(modalSheet).width,
                                maxWidth:
                                  window.getComputedStyle(modalSheet).maxWidth,
                                flexDirection:
                                  window.getComputedStyle(modalSheet)
                                    .flexDirection,
                              }
                            : null,
                          // 是否在视窗内
                          isInViewport:
                            rect.top >= 0 &&
                            rect.left >= 0 &&
                            rect.bottom <= window.innerHeight &&
                            rect.right <= window.innerWidth,
                          // 特殊检查：是否是顶部弹出
                          isTopModal:
                            modalSheet?.classList.contains('modal-sheet--top'),
                          isSnapPoints: modalSheet?.classList.contains(
                            'modal-sheet--snap-points'
                          ),
                          // 检查拖拽条在Modal中的相对位置
                          relativePosition: parentRect
                            ? {
                                isAtTop: rect.top <= parentRect.top + 50, // 在顶部50px内
                                isAtBottom:
                                  rect.bottom >= parentRect.bottom - 50, // 在底部50px内
                              }
                            : null,
                        });
                      } else {
                        console.log('🚨 拖拽区域DOM不存在！');
                      }
                    }, 50);
                  }

                  return shouldShow;
                })() && (
                  <div
                    ref={dragRef} // 绑定 dragRef 到拖拽区域
                    className='modal-sheet__drag-area'
                    data-debug={`draggable:${draggable},hasSnapPoints:${hasSnapPoints}`}
                    style={{
                      // 保留关键的显示修复
                      display: 'flex',
                      visibility: 'visible',
                      opacity: 1,
                    }}
                    // 🎯 无障碍支持
                    role='button'
                    tabIndex={0}
                    aria-label={
                      hasSnapPoints
                        ? '拖拽调整弹框大小或使用键盘箭头键切换吸附点'
                        : '拖拽移动弹框位置'
                    }
                    aria-describedby='modal-sheet-instructions'
                    // 🎮 键盘操作支持
                    onKeyDown={e => {
                      // 阻止键盘事件冒泡到其他元素
                      e.stopPropagation();

                      if (hasSnapPoints) {
                        // 🎯 Snap Points 键盘操作
                        switch (e.key) {
                          case 'ArrowUp':
                          case 'ArrowLeft':
                            e.preventDefault();
                            // 切换到上一个吸附点
                            if (currentSnapIndex > 0) {
                              snapTo(currentSnapIndex - 1);
                            }
                            break;
                          case 'ArrowDown':
                          case 'ArrowRight':
                            e.preventDefault();
                            // 切换到下一个吸附点
                            if (
                              currentSnapIndex <
                              (snapPoints?.length || 1) - 1
                            ) {
                              snapTo(currentSnapIndex + 1);
                            }
                            break;
                          case 'Home':
                            e.preventDefault();
                            // 跳转到第一个吸附点
                            snapTo(0);
                            break;
                          case 'End':
                            e.preventDefault();
                            // 跳转到最后一个吸附点
                            snapTo((snapPoints?.length || 1) - 1);
                            break;
                          case 'Enter':
                          case ' ':
                            e.preventDefault();
                            // 空格或回车键：开始拖拽模拟
                            console.log('🎮 键盘激活拖拽模式');
                            break;
                        }
                      } else if (draggable) {
                        // 🎯 自由拖拽键盘操作
                        const moveDistance = e.shiftKey ? 50 : 10; // Shift键加速移动
                        switch (e.key) {
                          case 'ArrowUp':
                            e.preventDefault();
                            console.log(
                              `🎮 键盘向上移动弹框 ${moveDistance}px`
                            );
                            // TODO: 实现键盘移动逻辑
                            break;
                          case 'ArrowDown':
                            e.preventDefault();
                            console.log(
                              `🎮 键盘向下移动弹框 ${moveDistance}px`
                            );
                            break;
                          case 'ArrowLeft':
                            e.preventDefault();
                            console.log(
                              `🎮 键盘向左移动弹框 ${moveDistance}px`
                            );
                            break;
                          case 'ArrowRight':
                            e.preventDefault();
                            console.log(
                              `🎮 键盘向右移动弹框 ${moveDistance}px`
                            );
                            break;
                        }
                      }
                    }}
                    // 顶部整块作为拖拽命中区：
                    // - 有吸附点：进入 snap 拖拽流程（计算尺寸）
                    // - 无吸附点但可拖拽：使用 Framer Motion 拖拽（已在 motion.div 上设置）
                    // - 高速拖拽时：使用原生事件处理
                    onMouseDown={
                      hasSnapPoints || (draggable && isHighSpeedDrag)
                        ? e => {
                            // 🔧 增强的冲突检测：检查是否点击了调整大小手柄或其子元素
                            const target = e.target as HTMLElement;
                            const isResizeHandle = target.closest(
                              '.modal-sheet__resize-handle'
                            );

                            if (isResizeHandle) {
                              console.log(
                                '🔧 拖拽区域：检测到调整大小手柄点击，阻止拖拽事件'
                              );
                              e.stopPropagation(); // 阻止事件冒泡到拖拽区域
                              return; // 让调整大小手柄处理事件
                            }

                            e.preventDefault();
                            e.stopPropagation();

                            if (hasSnapPoints) {
                              console.log('🎯 启动Snap Points拖拽');
                              handleSnapDragStart(e.nativeEvent);
                            } else if (draggable && isHighSpeedDrag) {
                              console.log('🚀 启动高速原生拖拽');
                              nativeHandleMouseDown(e);
                            }
                          }
                        : undefined
                    }
                    onTouchStart={
                      hasSnapPoints
                        ? e => {
                            // 🔧 增强的冲突检测：检查是否点击了调整大小手柄或其子元素
                            const target = e.target as HTMLElement;
                            const isResizeHandle = target.closest(
                              '.modal-sheet__resize-handle'
                            );

                            if (isResizeHandle) {
                              console.log(
                                '🔧 拖拽区域：检测到调整大小手柄触摸，阻止拖拽事件'
                              );
                              e.stopPropagation(); // 阻止事件冒泡到拖拽区域
                              return; // 让调整大小手柄处理事件
                            }

                            // 🎯 只处理 Snap Points 触摸拖拽
                            e.preventDefault();
                            e.stopPropagation();
                            console.log('🎯 启动Snap Points触摸拖拽');
                            handleSnapDragStart(e.nativeEvent);
                          }
                        : undefined
                    }
                  >
                    {/* 拖拽指示器：提示可拖拽，不拦截事件 */}
                    <div
                      className='modal-sheet__drag-indicator'
                      style={{
                        // 保留关键的显示修复
                        display: 'block',
                        visibility: 'visible',
                        opacity: 1,
                      }}
                    />
                  </div>
                )}

                {/* 🎮 键盘操作说明（屏幕阅读器用） */}
                <div
                  id='modal-sheet-instructions'
                  style={{
                    position: 'absolute',
                    left: '-10000px',
                    width: '1px',
                    height: '1px',
                    overflow: 'hidden',
                  }}
                >
                  {hasSnapPoints
                    ? '键盘操作：上下箭头键或左右箭头键切换吸附点，Home键跳转到第一个吸附点，End键跳转到最后一个吸附点，ESC键关闭弹框'
                    : draggable
                      ? '键盘操作：箭头键移动弹框位置，按住Shift键加速移动，ESC键关闭弹框'
                      : '键盘操作：ESC键关闭弹框'}
                </div>

                {children}
                {resizable &&
                  availableDirections.map(direction => {
                    console.log(
                      `🔧 渲染调整大小手柄: ${direction}, 位置: ${position}`
                    );
                    const handleProps = getResizeHandleProps(direction);
                    console.log(`🔧 手柄Props:`, handleProps);
                    console.log(`🔧 手柄事件检查:`, {
                      hasOnMouseDown:
                        typeof handleProps.onMouseDown === 'function',
                      hasOnTouchStart:
                        typeof handleProps.onTouchStart === 'function',
                      cursor: handleProps.style?.cursor,
                      dataDirection: handleProps['data-direction'],
                    });

                    // 创建一个测试函数来验证事件处理
                    const testMouseDown = (e: React.MouseEvent) => {
                      console.log(`🚨 测试mouseDown被调用: ${direction}`);
                      e.preventDefault();
                      e.stopPropagation();

                      // 调用原始的事件处理器
                      if (handleProps.onMouseDown) {
                        console.log(`🚨 调用原始onMouseDown: ${direction}`);
                        handleProps.onMouseDown(e);
                      } else {
                        console.log(`❌ 没有onMouseDown处理器: ${direction}`);
                      }
                    };
                    // Mouse Event 是处理鼠标交互的事件系统，专门用于桌面设备上的鼠标操作。
                    // Touch Event 是处理触摸屏交互的事件系统，专门用于移动设备和触摸屏设备。
                    return (
                      <div
                        key={direction}
                        className={`modal-sheet__resize-handle modal-sheet__resize-handle--${direction}`}
                        {...handleProps}
                        onMouseDown={testMouseDown} // 使用测试函数覆盖原始处理器
                        style={{
                          ...handleProps.style,
                          // 添加调试样式确保手柄可见
                          backgroundColor: 'rgba(255, 0, 0, 0.8) !important',
                          border: '3px solid red !important',
                          minWidth: '20px',
                          minHeight: '20px',
                          zIndex: 1000,
                          // 关键样式：确保手柄正确工作
                          position: 'absolute',
                          display: 'block',
                          visibility: 'visible',
                          opacity: 1,
                          pointerEvents: 'auto',
                        }}
                        onClick={e => {
                          console.log(`🔧 手柄被点击: ${direction}`);
                          e.preventDefault();
                          e.stopPropagation();
                        }}
                      />
                    );
                  })}
              </ModalSheetContext.Provider>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    );

    return createPortal(modalContent, portalContainer);
  }
);

export default ModalSheet;
